/**
 * 二维地图通用工具包
 */
import Map from "ol/Map.js";
import Tile from "ol/layer/Tile.js";
import View from "ol/View.js";
import Overlay from 'ol/Overlay.js';
import { defaults } from "ol/control";
import { Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';
import { Draw } from 'ol/interaction';
import { Polygon } from "ol/geom";
// import { getVectorContext } from "ol/render";
import Feature from "ol/feature";
import { Fill, Stroke, Style } from 'ol/style';
import { Tianditu, TileSuperMapRest, MeasureParameters, MeasureService } from "@supermap/iclient-ol";
import { map2DConfig } from "./mapConfig.js";

/**
 * 初始化二维地图
 * @param mapId 地图控件id
 */
const initMap2D = (mapId) => {
    return new Map({
        target: mapId ? mapId : "map",
        view: new View({
            center: map2DConfig.defaultCenter ? map2DConfig.defaultCenter : [116.35, 25.84],
            zoom: map2DConfig.defaultZoom ? map2DConfig.defaultZoom : 14,
            projection: map2DConfig.defaultProjection ? map2DConfig.defaultProjection : "EPSG:4326",
        }),
        logo: 'false',
        controls: defaults({ attribution: false, zoom: false, rotate: false }),
        // layers: layers,
    });
}
/**
 * 初始化二维天地图
 * @param map 地图对象
 * @param type 天地图类型:vec矢量、img影像
 */
const initTianditu = (map, type) => {
    if (!map) map = initMap2D();
    if (map) {
        const mapLayer = new Tile({
            opacity: 1,
            visible: true,
            source: new Tianditu({
                layerType: type ? type : 'vec',
                key: map2DConfig.tiandituKey ? map2DConfig.tiandituKey : "2c1c91a5b6e77ed459735a17f813c339",
                // projection: "EPSG:4326",
            }),
        })
        map.addLayer(mapLayer);
        const annoLayer = new Tile({
            opacity: 1,
            visible: true,
            source: new Tianditu({
                layerType: type ? type : 'vec',
                isLabel: true,
                key: map2DConfig.tiandituKey ? map2DConfig.tiandituKey : "2c1c91a5b6e77ed459735a17f813c339",
                // projection: "EPSG:4326",
            }),
        })
        map.addLayer(annoLayer);
        // 根据行政区划裁剪
        // fetch('dongying.json')
        //     .then(res =>res.json())
        //     .then((geoJson)=>{
        //         const polygon = new Polygon(geoJson.features[0].geometry.coordinates)
        //         // const geometry = polygon.transform('EPSG:4326','EPSG:3857')
        //         const geometry = polygon
        //         mapLayer.on('prerender',event => {
        //             const ctx = event.context
        //             const vecCtx= getVectorContext(event)
        //             ctx.save()
        //             vecCtx.setStyle(new Style({
        //                 fill: new Fill({
        //                     color:[0,0,0,0]
        //                 })
        //             }))
        //             vecCtx.drawGeometry(geometry)
        //             ctx.stroke()
        //             ctx.clip()
        //         })
        //         mapLayer.on('postrender',event => {
        //             const ctx = event.context;
        //             ctx.restore();
        //         })
        //         annoLayer.on('prerender',event => {
        //             const ctx = event.context
        //             const vecCtx= getVectorContext(event)
        //             ctx.save()
        //             vecCtx.setStyle(new Style({
        //                 fill: new Fill({
        //                     color:[0,0,0,0]
        //                 })
        //             }))
        //             vecCtx.drawGeometry(geometry)
        //             ctx.clip()
        //         })
        //         annoLayer.on('postrender',event => {
        //             const ctx = event.context;
        //             ctx.restore();
        //         })
        //     })
        reverseCover(map)
    }
}
/**
 * 初始化二维管网图层
 * @param map 地图对象
 */
const initPipe2D = (map) => {
    if (!map) map = initMap2D();
    if (map && map2DConfig.layers) {
        if (map2DConfig.layers.length > 0) {
            for (let i = 0; i < map2DConfig.layers.length; i++) {
                const layerInfo = map2DConfig.layers[i];
                const mapLayer = new Tile({
                    visible: layerInfo.show ? layerInfo.show : true,
                    source: new TileSuperMapRest({
                        url: layerInfo.mapUrl,
                        wrapX: true,
                        // projection: "EPSG:4326",
                        crossOrigin: 'anonymous'
                    }),
                    projection: "EPSG:4326",
                })
                map.addLayer(mapLayer)
            }
        }
    }
}
/**
 * 创建气泡
 * @param map 地图对象
 * @param params 气泡参数
 */
const createPopup = (map, params) => {
    if (!map) map = initMap2D();
    if (map) {
        const container = document.createElement('div');
        const overlay = new Overlay(({
            element: container,
            autoPan: true,
            autoPanAnimation: {
                duration: 250
            }
        }));
        container.innerHTML = params.content;
        map.addOverlay(overlay);
        // 结果显示位置
        overlay.setPosition(params.position); // [x,y]
    }
}
/**
 * 二维距离测量
 * @param map 地图对象
 */
const distanceMeasure = (map) => {
    if (!map) map = initMap2D();
    if (map && map2DConfig.layers) {
        const source = new VectorSource({ wrapX: false });
        const vectorLayer = new VectorLayer({
            source: source,
            style: new Style({
                stroke: new Stroke({
                    color: 'red',
                    width: 3
                })
            })
        });
        map.addLayer(vectorLayer);
        let feature;
        const interaction = new Draw({
            source: source,
            type: "LineString",
            style: new Style({
                stroke: new Stroke({
                    color: 'blue',
                    width: 2
                })
            })
        });
        interaction.on('drawstart', function (evt) {
            feature = evt.feature;
        });
        interaction.on('drawend', function (evt) {
            const distanceMeasureParam = new MeasureParameters(feature.getGeometry());
            new MeasureService(map2DConfig.layers[0].mapUrl, { measureMode: "" }).measureDistance(distanceMeasureParam, function (serviceResult) {
                // console.log(serviceResult.result.distance + "米");
                //测量结果显示位置
                const coordinate = evt.feature.getGeometry().getCoordinates()[evt.feature.getGeometry().getCoordinates().length - 1];
                // console.log(coordinate);
                createPopup(map, { content: serviceResult.result.distance + "米", position: coordinate });
            });
        });
        map.addInteraction(interaction);
    }
}
/**
 * 反向遮罩
 * @param map 地图对象
 */
const reverseCover = (map) => {
    if (!map) map = initMap2D();
    if (map) {
        const source = new VectorSource({ wrapX: false });
        const vectorLayer = new VectorLayer({
            source: source,
            style: new Style({
                fill: new Fill({
                    // color: 'rgba(8,31,63,0.3)'
                    color: 'rgba(232,236,235,0.5)'
                }),
                stroke: new Stroke({
                    // color: 'rgb(8,91,163)',
                    color: 'rgb(255,0,0,0.3)',
                    width: 2,
                    lineDash: [3, 5]
                })
            })
        });
        map.addLayer(vectorLayer);
        //根据行政区划裁剪
        fetch('reverse.json')
            .then(res => res.json())
            .then((geoJson) => {
                const polygon = new Polygon(geoJson.features[0].geometry.coordinates)
                // const geometry = polygon.transform('EPSG:4326','EPSG:3857')
                const convertFt = new Feature({ geometry: polygon });
                // vectorLayer.getsource().addFeature(convertFt);
                source.addFeature(convertFt);
            })
    }
}
export {
    initMap2D,
    initTianditu,
    initPipe2D,
    distanceMeasure,
}